using Godot;
using System;

public partial class VelocityComponent : Node
{
	[Export]
	public int maxSpeed = 40;
	[Export]
	public float acceleration = 5;

	Vector2 velocity = Vector2.Zero;

	//向玩家加速
	public void AccelerateToPlayer(){
		Node2D ownerNode2D = Owner as Node2D;
		if( ownerNode2D == null){
			return;
		}
		Node2D player = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if(player == null){
			return;
		}

		Vector2 direction = (player.GlobalPosition - ownerNode2D.GlobalPosition).Normalized();
		this.AccelerateInDirection(direction);
	}

	//方向加速
	public void AccelerateInDirection(Vector2 direction){
		Vector2 desiredVelocity = direction * maxSpeed;
		double a = Math.Exp(-acceleration * GetProcessDeltaTime());
		velocity = velocity.Lerp(desiredVelocity,1 - (float)a);
	}

	public void Decelerate(){
		this.AccelerateInDirection(Vector2.Zero);
	}

	//移动
	public void Move(CharacterBody2D characterBody){
		characterBody.Velocity = velocity;
		characterBody.MoveAndSlide();
		velocity = characterBody.Velocity;
	}








	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}
}
